const express = require('express')

const router = express.Router()
// const qs = require('qs')
// const request = require('request')
const { succJson, errJson } = require('../utils/sendJson')
const imgProcess = require('../utils/imgProcess')
// let Image=require('../models/image');
const { Image } = require('../models')
const { wechat } = require('../utils/wxValid')

router.use('/wxVaild', (req, res) => {
  wechat(req, res)
})
router.get('/test', (req, res, next) => res.status(400).json({
  code: -1,
  message: '测试403返回',
}))
// router.get('/createUser',(req,res)=>{
//     console.log(req.body);
//     res.render('tool/createUser',{title:"添加用户"});
// })
//
//
// router.post('/createUser',(req,res)=>{
//     let userObj=qs.parse(req.body);
//     let user=new User(userObj.user);
//     user.save((err,userData)=>{
//         req.flash("success").toString()
//         console.log(userData);
//         res.redirect('/tool/createUser');
//     });
//     // let user=new User();
//
// })
router.get('/upload', (req, res) => {
  res.render('tool/uploadTest', { imgUrl: req.query.imgUrl })
})
router.get('/test', (req, res) => {
  res.render('tool/test', { title: '测试' })
})
router.post('/test', (req, res) => {
  console.log(req.body)
  console.log(req.rawBody)
  res.json({
    code: 0,
    message: '啊哈哈',
    data: {
      a: req.body,
      b: req.rawBody,
    },
  })
})
router.post('/upload', (req, res) => {
  imgProcess(req, (err, fields, files) => {
    if (err) {
      console.log(req.get('X-Requested-With'), 'X-Requested-With')
      if ((fields && fields.callType === 'json') || req.get('X-Requested-With') === 'XMLHttpRequest') {
        res.json(errJson({}, req.flash('error').toString()))
      } else {
        res.redirect('/tool/upload')
      }
      return
    }
    req.flash('success', '上传成功')
    // 保存在mongodb中便于后台管理
    files.forEach((ctx) => {
      Image.create(ctx)
      // new Image(Object(ctx,{url:ctx.path})).save();
    })
    if ((fields && fields.callType === 'json') || req.get('X-Requested-With') === 'XMLHttpRequest') {
      res.json(succJson({ imgs: files }, req.flash('success').toString()))
    } else {
      res.redirect(`/tool/upload?imgUrl=${files[0].path}`)
    }
  })
})
module.exports = router
